package com.it.admin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.admin.service.AdminCategoryService;
import com.it.common.domain.dos.ArticleCategoryRelDO;
import com.it.common.domain.dos.CategoryDO;
import com.it.common.enums.ResponseCodeEnum;
import com.it.common.exception.BizException;
import com.it.common.mapper.ArticleCategoryRelMapper;
import com.it.common.mapper.CategoryMapper;
import com.it.common.model.vo.SelectRspVO;
import com.it.common.utils.PageResponse;
import com.it.common.utils.Response;
import lombok.extern.slf4j.Slf4j;
import com.it.admin.model.dto.category.AddCategoryDto;
import com.it.admin.model.dto.category.DeleteCategoryDto;
import com.it.admin.model.dto.category.FindCategoryPageListDto;
import com.it.admin.model.vo.category.FindCategoryPageListRspVO;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AdminCategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryDO> implements AdminCategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private ArticleCategoryRelMapper articleCategoryRelMapper;

    @Override
    public Response addCategory(AddCategoryDto addCategoryDto) {
        String categoryName = addCategoryDto.getName().trim();
        CategoryDO categoryDO = categoryMapper.selectByName(categoryName);
        if(Objects.nonNull(categoryDO)){
            log.info("分类名称，{}，此类已存在",categoryName);
            throw new BizException(ResponseCodeEnum.CATEGORY_NAME_IS_EXISTED);
        }
        String creator = SecurityContextHolder.getContext().getAuthentication().getName();//security上下文中获取
        CategoryDO category = CategoryDO.builder().name(categoryName).creator(creator).build();
        categoryMapper.insert(category);
        return Response.success();
    }

    @Override
    public PageResponse findCategoryPageList(FindCategoryPageListDto findCategoryPageListDto) {

        Long current = findCategoryPageListDto.getCurrent();
        Long size = findCategoryPageListDto.getSize();
        String name = findCategoryPageListDto.getName();
        LocalDate startDate = findCategoryPageListDto.getStartDate();
        LocalDate endDate = findCategoryPageListDto.getEndDate();

        //执行分页查询
        Page<CategoryDO> pageList = categoryMapper.selectPageList(current, size, name, startDate, endDate);
        List<CategoryDO> categoryDOS = pageList.getRecords();
        // DO 转 VO stream流实现
        List<FindCategoryPageListRspVO> vos = new ArrayList<>();
        if(Objects.nonNull(categoryDOS)){
            //还能简化
            vos = categoryDOS.stream().map(categoryDO -> {
                FindCategoryPageListRspVO fvo = new FindCategoryPageListRspVO();
                fvo.setId(categoryDO.getId());
                fvo.setName(categoryDO.getName());
                fvo.setCreateTime(categoryDO.getCreateTime());
                fvo.setCreator(categoryDO.getCreator());
                fvo.setArticlesTotal(categoryDO.getArticlesTotal());
                return fvo;
            }).collect(Collectors.toList());
        }
        return PageResponse.success(pageList, vos);
    }


    /**
     * 逻辑删除
     * @param deleteCategoryDto
     * @return
     */
    @Override
    public Response deleteCategory(DeleteCategoryDto deleteCategoryDto) {
        Long id = deleteCategoryDto.getId();

        ArticleCategoryRelDO articleCategoryRelDO = articleCategoryRelMapper.selectOneByCategoryId(id);
        if(Objects.nonNull(articleCategoryRelDO)){
            log.warn("==> 此分类下包含文章，无法删除，categoryId: {}", id);
            throw new BizException(ResponseCodeEnum.CATEGORY_CAN_NOT_DELETE);
        }
        categoryMapper.deleteById(id);
        return Response.success();
    }

    /**
     * 下拉分类查询
     * @return {@link Response }
     */
    @Override
    public Response findCategorySelectList() {
        List<CategoryDO> categoryDOS = categoryMapper.findCategorySelectList();
        // DO 转 VO
        List<SelectRspVO> selectRspVOS = new ArrayList<>();
        if(Objects.nonNull(categoryDOS)){
            selectRspVOS = categoryDOS.stream().map(categoryDO -> {
                SelectRspVO svo = new SelectRspVO();
                svo.setLabel(categoryDO.getName());
                svo.setValue(categoryDO.getId());
                return svo;
            }).collect(Collectors.toList());
        }
        return Response.success(selectRspVOS);
    }
}
